<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of CustomFieldGroupController
 *
 * @author Poh Nean
 */
class CustomFieldGroupController extends PsController {

	public $layout = 'manage';

	public function accessRules() {
		return CMap::mergeArray(array(
					array('allow',
						'roles' => array('ManageAgency.CustomField.Manage'),
					),
						), parent::accessRules());
	}

	public function actionCreate($model = 'Contact') {
		$customFieldModels = CustomFieldModel::getCustomFieldModels();
		if (!in_array($model, $customFieldModels)) {
			throw new CHttpException(400, 'Invalid request');
		}

		$customFieldGroup = new CustomFieldGroup;
		$customFieldGroup->custom_field_model = $model;
		$selectedAgency = Yii::app()->user->getSelectedAgency();
		$agencyId = $selectedAgency->id;

		if (isset($_POST['CustomFieldGroup'])) {
			$customFieldGroup->attributes = $_POST["CustomFieldGroup"];
			$customFieldGroup->agency_id = $agencyId;
			$customFieldGroup->custom_field_model = $model;
			$isValid = $customFieldGroup->validate();

			if ($isValid) {
				$transaction = Yii::app()->db->beginTransaction();

				try {
					$customFieldGroup->save(false);

					// create or update custom field table
					$transaction->commit();
					PsSystemMessage::add('Custom field group added.', 'success');
				} catch (CDbException $e) {
					dump($e);
					$transaction->rollback();
					PsSystemMessage::add('Error adding custom group field.', 'error');
				}
				$this->redirect(array('customFieldGroup/index', 'type' => $model));
			}
		}

		$data = array();
		$data['customFieldGroup'] = $customFieldGroup;

		$this->render('create', $data);
	}

	public function actionDelete($id) {
		$response = array();

		$customFieldGroup = $this->loadCustomFieldGroup($id);
		if ($customFieldGroup->delete()) {
			$response["result"] = "success";
			$response["successMsg"] = "Custom field group deleted.";
		} else {
			$response["result"] = "failure";
			$response["errorMsg"] = "Error deleting custom field group.";
		}
		print CJSON::encode($response);
	}

	public function actionUpdate($id) {		
		$customFieldGroup = $this->loadCustomFieldGroup($id);
		
		if (isset($_POST['CustomFieldGroup'])) {
			$transaction = Yii::app()->db->beginTransaction();

			try {
				$customFieldGroup->attributes = $_POST["CustomFieldGroup"];
				$selectedAgency = Yii::app()->user->getSelectedAgency();
				$agencyId = $selectedAgency->id;
				$customFieldGroup->agency_id = $agencyId;

				$isValid = $customFieldGroup->validate();
				if ($isValid) {
					$customFieldGroup->save();
				}
				$transaction->commit();
				PsSystemMessage::add('Custom field group updated.', 'success');
			} catch (CDbException $e) {
				$transaction->rollback();
				PsSystemMessage::add('Custom field group not updated.', 'failure');
			}
			$this->redirect(array('customFieldGroup/index', 'type' => $customFieldGroup->custom_field_model));
		}
		
		$data = array();
		$data['customFieldModel'] = $customFieldGroup->custom_field_model;
		$data['customFieldGroup'] = $customFieldGroup;
		$this->render('update', $data);
	}

	public function actionIndex($model = 'Contact') {

		$customFieldModels = CustomFieldModel::getCustomFieldModels();
		if (!in_array($model, $customFieldModels)) {
			throw new CHttpException(400, 'Invalid request');
		}
		
		$selectedAgency = Yii::app()->user->getSelectedAgency();

		$criteria = new CDbCriteria;
		if ($selectedAgency->type == 'Franchise') {
			$criteria->addInCondition('t.agency_id', $selectedAgency->getChildAgencyIds());
		} else {
			$criteria->compare('t.agency_id', $selectedAgency->id);
		}

		$page = new CPagination;
		$page->pageSize = isset($_GET['pagesize']) ? $_GET['pagesize'] : 50;

		$sort = new CSort;
		$sort->defaultOrder = 't.pos ASC';

		$dataProvider = new CActiveDataProvider('CustomFieldGroup', array(
			'criteria' => $criteria,
			'sort' => $sort,
			'pagination' => $page
		));

		if ($model != '') {
			$criteria = $dataProvider->getCriteria();
			$criteria->compare('t.custom_field_model', $model);
			$dataProvider->setCriteria($criteria);
		}

		$data = array();
		$data['customFieldModel'] = $model;
		$data['dataProvider'] = $dataProvider;

		$this->render('index', $data);
	}

	public function loadCustomFieldGroup($id) {
		$model = CustomFieldGroup::model()->ofCurrentAgency()->findByPk($id);

		if ($model == null) {
			throw new PsPageNotFoundException();
		}

		return $model;
	}

}

?>
